using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using RecastUnity;
using System;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class MainCityNavigationCtrl : TNavigationController
    {
        public MainCityRegionCtrl regionCtrl => parent as MainCityRegionCtrl;

        protected override bool isActiveRecastObstacle => true;

        protected override void OnModuleGameplayInit()
        {
            regionCtrl.sceneCtrl.AddFirstPreloadAfterScene(LoadRecast);
        }

        protected override void OnSceneLoaded()
        {

        }

        private async UniTask LoadRecast()
        {
            if (_navMeshScene != IntPtr.Zero)
            {
                RecastDll.RecastClear(_navMeshScene);
            }
            var path = PathConstant.GetNavMeshCfg(regionCtrl.cfgScene.NavMesh);
            var resloader = ResLoader.Create();
            var text = await resloader.LoadABAssetAwait<TextAsset>(path);
            if (text == null)
            {
                LogGame.LogError("Load NavMesh failed:" + path);
            }
            var bytes = text.bytes;
            resloader.Put2Pool();

            _navMeshScene = RecastDll.RecastLoad(RecastDllID.MainCityView, bytes, bytes.Length, true);

            if (_navMeshScene == IntPtr.Zero)
            {
                LogGame.LogError("Init NavMesh failed." + path);
                return;
            }

            //获取边界
            if (RecastUtility.RecastTryGetBounds(_navMeshScene, out var b))
            {
                bounds = b;
                var min = bounds.min;
                var size = bounds.size;
                boundsRect = new Rect(min.x, min.z, size.x, size.z);
            }
            else
            {
                LogGame.LogError("NavMesh get bounds failed");
            }

#if UNITY_EDITOR
            GamePlayDebugUtil.RefreshNavMeshPreview(GameplayAreaType.MainCity, _navMeshScene);
#endif
        }

        protected override void OnDispose()
        {
            base.OnDispose();
        }
    }
}
